<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree v-bind:tree-data="treeData" v-on:appTreeClick="treeClickHandle"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>中心名称：<el-input placeholder="请输入部门名称" v-model="queryData.name"  clearable class="dzy-custom-input"></el-input></div>
            <div>层级：
              <el-select v-model="queryData.level" clearable placeholder="请选择">
                <el-option v-for="(item,index) in deptOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>负责人姓名：<el-input placeholder="请输入部门名称" v-model="queryData.chargeName"  clearable class="dzy-custom-input"></el-input></div>
            <div><el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button></div>
          </div>
        </el-header>
        <el-main>
          <app-table
            :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows" />
          <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" :before-close="cancel">
            <el-form :model="formData" :rules="rules" ref="formData" :disabled="showOnly" label-width="120px" size="mini">
              <el-form-item label="所属区域：" prop="regionIdArr">
                <div class="block">
                  <el-cascader
                    placeholder="请选择"
                    :options="regionTreeData"
                    :props="regionIdProps"
                    filterable
                    clearable
                    change-on-select
                    :show-all-levels="false"
                    v-model="formData.regionIdArr"
                    @change="regionChangedEvt">
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="上级部门：" prop="deptIdArr">
                <div class="block">
                  <el-cascader
                    placeholder="请选择"
                    :options="treeData"
                    :props="regionIdProps"
                    filterable
                    clearable
                    change-on-select
                    :show-all-levels="false"
                    v-model="formData.deptIdArr"
                    @change="deptChangedEvt">
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="部门编号：">
                <el-input  v-model="formData.deptCode" placeholder="请输入部门编号"></el-input>
              </el-form-item>
              <el-form-item label="名称：" prop="name">
                <el-input  v-model="formData.name" placeholder="请输入部门名称"></el-input>
              </el-form-item>
              <el-form-item label="联系方式：" prop="name">
                <el-input  v-model="formData.deptPhone" placeholder="请输入联系方式"></el-input>
              </el-form-item>
              <el-form-item label="第一责任人">
                <el-input  v-model="formData.firstChargeId" placeholder="请输入责任人"></el-input>
              </el-form-item>
              <el-form-item label="第一负责人">
                <el-input  v-model="formData.firstResponsibilityId" placeholder="请输入负责人"></el-input>
              </el-form-item>
              <el-form-item label="组成单位：" prop="name">
                <el-input  v-model="formData.component" placeholder="请输入组成单位"></el-input>
              </el-form-item>
              <el-form-item label="所在地：" prop="name">
                <el-input  v-model="formData.address" placeholder="请输入所在地"></el-input>
              </el-form-item>
              <el-form-item label="所在地祥址：" prop="name">
                <el-input  v-model="formData.addressDetail" placeholder="请输入所在地祥址"></el-input>
              </el-form-item>
            </el-form>
            <div v-if="!showOnly" slot="footer" class="dialog-footer">
              <el-button @click="cancel('formData')">取 消</el-button>
              <el-button type="primary" @click="save('formData')" >提 交</el-button>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import CascaderTree from '@/components/CascaderTree'
import AppTree from '@/components/common/AppTree'
import BtnGroup from '@/components/BtnGroup'
import AppTable from '@/components/AppTable'
import {getAllRegion} from '@/utils/region'
import {getUserRegionTree} from '@/utils/LocalDataUtil'
import {getDictDataOption} from '@/utils/getDictDataOption'
import {getUserDeptTree, setUserDeptTree} from '@/utils/SessionDataUtil'
import {findDept, getDeptTree, createDept, updateDept, deleteDept, listRegion, listDept, getRegionByDept, getDeptByRegion} from '@/http/AppApi'
export default {
  data () {
    return {
      tableData: [],
      pageData: {},
      formData: {
        regionId: '',
        parentId: '',
        deptCode: '',
        name: ''
      },
      regionIdProps: {
        label: 'name',
        value: 'id'
      },
      treeData: [],
      queryData: {},
      allDeptData: [],
      allRegionData: [],
      dialogTitle: '',
      dialogFormVisible: false,
      currentSelectedData: [],
      showOnly: false,
      regionTreeData: [],
      tableColumns: [
        { label: '部门分类', prop: 'deptCategoryName' },
        { label: '部门层级', prop: 'level', formatter: this.levelFormatter },
        { label: '部门名称', prop: 'name' },
        { label: '所属区域', prop: 'regionName' },
        { label: '上级部门', prop: 'parentName' }
      ],
      rules: {
        regionIdArr: [{
          required: true,
          message: '请选择所属区域',
          trigger: 'blur'
        }],
        parentId: [{
          required: true,
          message: '请选择上级部门',
          trigger: 'blur'
        }],
        name: [{
          required: true,
          message: '请输入部门名称',
          trigger: 'blur'
        }]
      },
      deptOption: []
    }
  },
  components: {
    BtnGroup,
    AppTable,
    AppTree,
    CascaderTree
  },
  mounted () {
    this.getTableData()
    this.getTreeData()
    this.getRegionTreeData()
    this.deptOption = getDictDataOption('层级')
  },
  methods: {
    levelFormatter (row, column) {
      let centerLevelOption = getDictDataOption('层级')
      let resGenterLevel = ''
      for (let i = 0; i < centerLevelOption.length; i++) {
        if (centerLevelOption[i].code === row.level) {
          resGenterLevel = centerLevelOption[i].name
          break
        }
      }
      return resGenterLevel
    },
    regionChangedEvt (val) {
      if (val && val.length > 0) {
        let len = val.length - 1
        let regionId = val[len]
        let m = this
        getDeptByRegion(regionId).then(resp => {
          if (resp.code === '200') {
            let deptData = {}
            deptData.id = resp.data.id
            deptData.items = m.treeData
            let deptIdArr = getAllRegion(deptData)
            m.$set(m.formData, 'deptIdArr', deptIdArr)
          } else if (resp.code === '1021') {
            return ''
          }
        })
      } else {
        this.getTreeData()
      }
    },
    deptChangedEvt (val) {
      if (val && val.length > 0) {
        let len = val.length - 1
        let deptId = val[len]
        let m = this
        getRegionByDept(deptId).then(resp => {
          if (resp.code === '200') {
            if (resp.data.length !== 0) m.regionTreeData = resp.data
            return false
          }
        })
      } else {
        this.$set(this.formData, 'regionIdArr', [])
        this.getRegionTreeData()
      }
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formData) {
            if (this.formData.regionIdArr && this.formData.regionIdArr.length > 0) {
              let len = this.formData.regionIdArr.length - 1
              this.formData.regionId = this.formData.regionIdArr[len]
            }
            if (this.formData.deptIdArr && this.formData.deptIdArr.length > 0) {
              let len = this.formData.deptIdArr.length - 1
              this.formData.parentId = this.formData.deptIdArr[len]
            }
            if (this.formData.id) {
              updateDept(this.formData).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.getTableData()
                  this.reloadTreeData()
                  this.cancel()
                  this.$message({
                    showClose: true,
                    message: '修改成功',
                    type: 'success'
                  })
                } else {
                  this.$message({
                    type: 'info',
                    message: resp.message
                  })
                }
              })
            } else {
              createDept(this.formData).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.getTableData()
                  this.reloadTreeData()
                  this.cancel()
                  this.$refs[formName].resetFields()
                  this.$message({
                    showClose: true,
                    message: '新增成功',
                    type: 'success'
                  })
                } else {
                  this.$message({
                    type: 'info',
                    message: resp.message
                  })
                }
              })
            }
          }
        } else {
          return false
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deleteDept(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.reloadTreeData()
                this.$message({
                  showClose: true,
                  message: '删除成功',
                  type: 'success'
                })
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancel (formName) {
      this.dialogFormVisible = false
      this.formData = {}
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
    },
    getTableData () {
      let param = this.queryData
      findDept(param).then(resp => {
        if (resp.code && resp.code === '200') {
          this.pageData = resp.data
          if (this.pageData.items && this.pageData.items instanceof Array) {
            this.tableData = this.pageData.items
          }
        }
      })
    },
    getTreeData () {
      let data = getUserDeptTree()
      if (data && data instanceof Array) {
        setUserDeptTree(data)
        this.treeData = data
      }
    },
    getRegionTreeData () {
      let regionTreeData = getUserRegionTree()
      if (regionTreeData && regionTreeData instanceof Array) {
        this.regionTreeData = regionTreeData
      }
    },
    reloadTreeData () {
      getDeptTree().then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data && data instanceof Array) {
            setUserDeptTree(data)
            this.treeData = data
          }
        }
      })
    },
    beforeSubmit () {
      return false
    },
    handleCurrentChange (val) {
      this.queryData.offset = (val - 1) * 10
      this.getTableData()
    },
    getAllRegionData () {
      listRegion().then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data && data instanceof Array) {
            this.allRegionData = data
          }
        }
      })
    },
    getAllDeptData () {
      listDept().then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data && data instanceof Array) {
            this.allDeptData = data
          }
        }
      })
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        this.getAllRegionData()
        this.getAllDeptData()
        if (callbackData.btnType === 'post') {
          if (this.formData.deptIdArr && this.formData.deptIdArr.length > 0) {
            let arr = this.formData.deptIdArr
            this.formData = {}
            this.$set(this.formData, 'deptIdArr', arr)
          }
        } else {
          this.formData = callbackData.rows[0]
          if (this.formData.parentId) {
            let deptData = {}
            deptData.id = this.formData.parentId
            deptData.items = this.treeData
            let deptIdArr = getAllRegion(deptData)
            this.$set(this.formData, 'deptIdArr', deptIdArr)
          }
          if (this.formData.regionId) {
            let regionData = {}
            regionData.id = this.formData.regionId
            regionData.items = this.regionTreeData
            let regionIdArr = getAllRegion(regionData)
            this.$set(this.formData, 'regionIdArr', regionIdArr)
          }
        }
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
      } else {
        this.currentSelectedData = []
        this.formData = []
      }
    },
    treeClickHandle (data) {
      this.queryData.likeId = data.id
      this.queryData.offset = 0
      let deptData = {}
      deptData.id = data.id
      deptData.items = this.treeData
      let deptIdArr = getAllRegion(deptData)
      this.$set(this.formData, 'deptIdArr', deptIdArr)
      this.deptChangedEvt(deptIdArr)
      this.getTableData()
    },
    searchHandleClick () {
      this.queryData.offset = 0
      this.getTableData()
    }
  },
  computed: {},
  watch: {}
}
</script>
<style>
</style>
